<template>
    <div>
        <el-upload
                action=""
                :http-request="addFileToQueue"
                :multiple="true"
                :show-file-list="false">
            <slot></slot>
        </el-upload>
        <div v-if="loading" class="loading-bg flex-row flex-center">
            <i class="icon el-icon-loading"></i>
            <div>{{progress}}%</div>
            <el-button size="mini" style="margin-left: 10px" @click="cancel">取消</el-button>
        </div>
    </div>
</template>

<script>
import axios from 'axios';
import {getStorage} from '@/utils/storage';
import {responseError, responseResolve, apiBase} from '@/http/config';

export default {
  name: 'file-uplaod',
  props: {
    id: {
      required: true
    }
  },
  data() {
    return {
      loading: false,
      progress: 0,
      source: null,
      fileQueue: [],
      timer: null
    }
  },
  methods: {
    cancel() {
      this.fileQueue = []
      this.source.cancel('取消上传')
    },
    addFileToQueue(data) {
      this.fileQueue.push(data)
      if (this.timer) {
        clearTimeout(this.timer)
        this.timer = null
      }
      this.timer = setTimeout(() => {
        this.handleQueue()
      }, 50)
    },
    handleQueue() {
      if (this.fileQueue.length) {
        const File = this.fileQueue.shift()
        if (File.file.size > 2 * 1024 * 1024 * 1024) {
          this.$TZmessage.error(`文件${File.file.name}超过了2GB，已忽略`)
          this.handleQueue()
        } else {
          this.loading = true
          this.uploadFile(File).catch(err => {
            this.$TZmessage.error(err.msg || `文件${File.file.name}上传失败`)
          }).finally(() => {
            this.loading = false
            this.handleQueue()
          })
        }
      } else {
        this.$emit('finish')
      }
    },
    uploadFile(data) {
      this.source = axios.CancelToken.source()
      const request = axios.create({
        baseURL: apiBase,
        withCredentials: false,
        timeout: 1000 * 3600 * 2,
        headers: {
          'X-Requested-With': 'XMLHttpRequest',
          Accept: 'application/json',
        },
        cancelToken: this.source.token
      });
      request.interceptors.request.use(
        config => {
          const token = getStorage('token')
          if (token) {
            config.headers.token = token;
          }
          return config;
        },
        err => Promise.reject(err),
      );
      request.interceptors.response.use(
        responseResolve,
        responseError,
      );

      this.progress = `${data.file.name}已上传：${0}%`
      let fd = new FormData()
      fd.append('file', data.file)
      fd.append('parentId', this.id)
      let config = {
        timeout: 1000 * 3600 * 2,
        onUploadProgress: progressEvent => {
          this.progress = data.file.name + '已上传：' + Math.round(Math.min((progressEvent.loaded / progressEvent.total) * 100, 99) * 100) / 100 || 0
        }
      }
      return request.post('/file/fileUpload', fd, config)
    }
  },
  mounted() {
  }
}
</script>

<style lang="scss" scoped>
    .loading-bg {
        width: 100vw;
        height: 100vh;
        position: fixed;
        z-index: 99999;
        background: rgba(0,0,0,.4);
        left: 0;
        top: 0;
        color: #ffffff;
        .icon {
            font-size: 30px;
            padding: 10px;
        }
    }
</style>